package com.xxs.method;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;

import com.xxs.common.Const;
import com.xxs.utils.xml.Fields;
import com.xxs.utils.xml.XmlDom4jUtils;

@SuppressWarnings("unchecked")
public class QueryUtils {
	
	/**
	 * 获取模型专用
	 * @param sitecode  站点编码
	 * @param modelname	模型名称
	 * @return
	 */
	public List<Element> getElementsBySitecodeAndModename(String sitecode,String modelname){
		return XmlDom4jUtils.getElements(getXmlPath(sitecode, "model"),modelname);
	}
	/**
	 * 获取站点相关的对象数据专用
	 * @param sitecode  站点编码
	 * @param modelname	模型名称
	 * @return
	 */
	public List<Element> getElementsBySitecodeAndModenames(String sitecode,String modelname){
		return XmlDom4jUtils.getElements(getXmlPath(sitecode, modelname),modelname);
	}
	/**
	 * 返回Fields对象，便于页头显示
	 * @param modelname 具体的模型名称
	 * @return
	 */
	public List<Fields> getFieldsByModename(String modelname) {
		return XmlDom4jUtils.getFields(Const.SYSTEM_TABLES_PATH,modelname);
	}

	public List<Element> getElementsByAttrAndValue(String sitecode,String modelName,String attrName,String attrValue){ 
		Document document = XmlDom4jUtils.getDocument(getXmlPath(sitecode,modelName));
		return document.selectNodes("//"+modelName+"[@"+attrName+"='"+attrValue+"']");
	}
	
	public String getValueByAttrAndValue(String sitecode,String modelName,String beanName,String attrName,String attrValue,String outAttrName){ 
    	Document document = XmlDom4jUtils.getDocument(getXmlPath(sitecode,modelName));
    	List<Element> lists = document.selectNodes("//"+beanName+"[@"+attrName+"='"+attrValue+"']");
    	if(lists!=null && lists.size()>0){
    		return lists.get(0).attributeValue(outAttrName);
    	}else{
    		return null;
    	}
    }
	
	public static String getCurrentSiteName(String siteId) {
		String siteName = XmlDom4jUtils.getParaValueByAttrAndValue(Const.SITE_PATH,"site","id",siteId,"name");
		return siteName != null ? siteName : null;
	}
	
	public static String getCurrentSiteCode(String siteId) {
		String siteCode = XmlDom4jUtils.getParaValueByAttrAndValue(Const.SITE_PATH,"site","id",siteId,"code");
		return siteCode != null ? siteCode : null;
	}
	public String getXmlPath(String siteCode,String modelName){
		if(siteCode!=null){
			return Const.XML_PREFIX+siteCode+"/"+modelName+Const.XML_SUFFIX;
		}else{
			return Const.XML_PREFIX+modelName+Const.XML_SUFFIX;
		}
	}
}
